package com.yy.filter;

import base.CommonConstans;
import com.alibaba.fastjson.JSON;
import com.google.common.net.HttpHeaders;
import enums.ResponseEnum;
import exception.TokenException;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.util.CollectionUtils;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
import utils.CurrentLoginUser;
import utils.JWTUtils;
import base.Result;

import java.nio.charset.StandardCharsets;
import java.util.List;

/**
 * @Author: lyy
 * Date: 2021/12/13 16:20
 */
@Slf4j
@Configuration
public class AccessFilter implements GlobalFilter, Ordered {

	@Override
	public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
		Integer userId;
		try {
			String token = getToken(exchange);
			userId = JWTUtils.parseToken(token);
		} catch (TokenException e) {
			return getVoidMono(exchange, ResponseEnum.NOT_TOKEN);
		} catch (Exception e) {
			return getVoidMono(exchange, ResponseEnum.TOKEN_EXCEPTION);
		}
		CurrentLoginUser loginUser = CurrentLoginUser.builder().userId(userId).build() ;
		ServerHttpRequest mutatedRequest = exchange.getRequest().mutate().header(CommonConstans.CLIENT_HEAD, JSON.toJSONString(loginUser)).build();
		exchange.mutate().request(mutatedRequest).build();
		return chain.filter(exchange);
	}

	@Override
	public int getOrder() {
		return 0;
	}

	private String getToken(ServerWebExchange exchange){
		ServerHttpRequest request = exchange.getRequest();
		List<String> headList = request.getHeaders().get(HttpHeaders.AUTHORIZATION);
		if(CollectionUtils.isEmpty(headList)){
			throw new TokenException(ResponseEnum.NOT_TOKEN.getMessage());
		}
		String requestToken = headList.stream().findFirst().orElseGet(null);
		if(StringUtils.isEmpty(requestToken)){
			throw new TokenException(ResponseEnum.NOT_TOKEN.getMessage());
		}
		// 去掉 Bearer
		String token = requestToken.replace(CommonConstans.TOKEN_DEFAULT_HEAD, "").trim();
		return token;
	}

	public Mono<Void> getVoidMono(ServerWebExchange exchange, ResponseEnum responseEnum){
		DataBuffer buffer = exchange.getResponse().bufferFactory().wrap(JSON.toJSONString(Result.error(responseEnum)).getBytes(StandardCharsets.UTF_8));
		return exchange.getResponse().writeWith(Flux.just(buffer));
	}

}
